package com.rongji.cms.tools.websocket.handler;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.rongji.cms.tools.common.utils.JsonUtils;
import com.rongji.cms.tools.common.utils.StringUtils;
import com.rongji.cms.tools.websocket.constants.WsConstant;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author yang
 * @date 2023/2/7 9:55
 * @description
 */

@Component
@Slf4j
public class MessageEventHandler {


    public static ConcurrentMap<String, SocketIOClient> socketIOClientMap = new ConcurrentHashMap<>();


    @Resource
    private RedissonClient redisson;

    @Resource
    private SocketIOServer socketIoServer;

    @OnConnect
    public void  onConnect(SocketIOClient client){
        Map<String,Object> clientMap = new HashMap<>(16);
        if(client!=null){
            String room = client.getHandshakeData().getSingleUrlParam("room");
            String nameSpace = client.getNamespace().getName();
            String sessionId = client.getSessionId().toString();
            log.info("socket连接成功, room={}, sessionId={},namespace={}",room,sessionId,nameSpace);
            if(StringUtils.isNotBlank(room)){
                client.joinRoom(room);
                clientMap.put("rooms",room);
            }
            clientMap.put("createTime", LocalDateTime.now().toString());
            redisson.getBucket(WsConstant.KEY_ROOM_PREFIX+sessionId).trySet(clientMap);
        }
    }

    /**
     * 客户端关闭连接时触发
     *
     * @param client
     */
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        log.info("客户端:" + client.getSessionId() + "断开连接");
    }

    /**
     * 客户端事件
     *
     * @param client  　客户端信息
     * @param request 请求信息
     * @param msg    　客户端发送数据
     */
    @OnEvent(value = "messageevent")
    public void onEvent(SocketIOClient client, AckRequest request, String msg) {
        log.info("发来消息：" + msg);
        //回发消息

        JSONObject jsonObject = JSONUtil.parseObj(msg);
        String message = jsonObject.getStr("message");
        Collection<SocketIOClient> clients = socketIoServer.getBroadcastOperations().getClients();
        for (SocketIOClient clientByRoom : clients) {
            clientByRoom.sendEvent("messageevent", client.getSessionId().toString()+":   "+message);
        }
    }

    @OnEvent(value = "test")
    public void onEvent(SocketIOClient client, String msg) {
        log.info("test发来消息：" + msg);
        //回发消息

        JSONObject jsonObject = JSONUtil.parseObj(msg);
        String message = jsonObject.getStr("message");
        Collection<SocketIOClient> clients = socketIoServer.getBroadcastOperations().getClients();
        for (SocketIOClient clientByRoom : clients) {
            clientByRoom.sendEvent("test",    message);
        }
    }

}
